# coding=utf-8
# @File  : sync_private_world.py.py
# @Author: WUXY
# @Date  : 2019/1/14
# @Desc  :

#coding=utf-8
import os
import datetime
from flask_script import Command
from common.utils import *
from dbs.models import *
from common.write_log import writelog
from controller.synchronization_controller import SynchronizationController


# 自动私有世界物体
class SyncPrivateWorldCommand(Command):

    def run(self):
        if self.__get_lock():
            try:
                sync = SynchronizationController()
                count = sync.synchronous_private_data()
            except:
                writelog(traceback)
            self.__release_lock()

    def __get_lock(self):
        result = False
        try:
            shell_dir = os.path.dirname(__file__)
            lock_file = os.path.realpath(os.path.join(shell_dir, 'sync.lock'))
            if not os.path.exists(lock_file):
                fp = open(lock_file, 'w')
                fp.write(str(datetime.datetime.now()))
                fp.close()
                cmd = 'chmod 777 %s' % lock_file
                os.system(cmd)
                result = True
        except:
            writelog(traceback.format_exc())
        return result

    def __release_lock(self):
        result = False
        try:
            shell_dir = os.path.dirname(__file__)
            lock_file = os.path.realpath(os.path.join(shell_dir, 'sync.lock'))
            bk_file = os.path.realpath(os.path.join(shell_dir, 'sync-bk.lock'))
            if os.path.exists(lock_file):
                os.rename(lock_file, bk_file)
                result = True
        except:
            writelog(traceback.format_exc())
        return result
